package com.homedo.microservice.distributed.id.service.config;

import com.homedo.common.exception.HomedoException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.io.IOException;

@ControllerAdvice
public class LocalResponseBodyAdvice implements ResponseBodyAdvice {
    private static final Logger _LOGGER = LoggerFactory.getLogger(LocalResponseBodyAdvice.class);
    private StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();

    @Override
    public Object beforeBodyWrite(Object returnValue, MethodParameter methodParameter,
                                  MediaType mediaType, Class clazz, ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        if (returnValue instanceof String
                && (methodParameter.hasMethodAnnotation(ResponseBody.class)
                || methodParameter.getMethod().getDeclaringClass().isAnnotationPresent(RestController.class))) {
            try {
                stringHttpMessageConverter.write((String) returnValue, MediaType.TEXT_PLAIN, serverHttpResponse);
            } catch (IOException e) {
                _LOGGER.error("[解析返回值异常:{}]", e.getMessage(), e);
                throw new HomedoException("[解析返回值异常:" + e.getMessage() + "]");
            }

            return null;
        }

        return returnValue;
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Class clas) {

//        if (methodParameter.getDeclaringClass().equals(String.class)
//                && (methodParameter.hasMethodAnnotation(ResponseBody.class)
//                || methodParameter.getMethod().getDeclaringClass().isAnnotationPresent(RestController.class))) {
//            return true;
//        }

//        return false;
        return true;
    }
}